/**
 * Copyright 2010 TechDive.in
 *  
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at
 *
 * <a href="http://www.apache.org/licenses/LICENSE-2.0" title="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a> 
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
 * See the License for the specific language governing permissions and 
 * limitations under the License.  
 *   
 */

 /**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package controlador;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Vector;
import modelo.Info;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;
import org.snmp4j.transport.DefaultUdpTransportMapping;

public class SnmpControlador
{
  // private static String  ipAddress  = "192.168.0.1";
  // private static String  port    = "161";
  // OID of MIB RFC 1213; Scalar Object = .iso.org.dod.internet.mgmt.mib-2.system.sysDescr.0
  private static int    snmpVersion  = SnmpConstants.version1;
  //  private static String  community  = "fmat-mnrt";

    public void main(String[] args) throws Exception{
        snmp("192.168.0.1","161","fmat");
    }

    public ArrayList<Info> snmp(String ipAddress,String port,String community) throws IOException{
        //    System.out.println("SNMP GET Demo");
        // Create TransportMapping and Listen
        TransportMapping transport = new DefaultUdpTransportMapping();
        transport.listen();

        // Create Target Address object
        CommunityTarget comtarget = new CommunityTarget();
        comtarget.setCommunity(new OctetString(community));
        comtarget.setVersion(snmpVersion);
        comtarget.setAddress(new UdpAddress(ipAddress + "/" + port));
        comtarget.setRetries(2);
        comtarget.setTimeout(1000);
        Snmp snmp = new Snmp(transport);
        PDU pdu = new PDU();
        ArrayList<Info> info=new ArrayList<Info>();
        String modelo="1.3.6.1.2.1.1.1.0";
        
        pdu.add(new VariableBinding(new OID(modelo)));
        pdu.setType(PDU.GET);
        pdu.setRequestID(new Integer32(1));
        
        ResponseEvent response = snmp.get(pdu, comtarget);
        PDU responsePDU = response.getResponse();
        
        String split[]=responsePDU.getVariableBindings().
                get(0).toString().split(",");
        String model[]=split[1].split(" ");
        pdu.remove(0);
        if(model[1].compareTo("C3550")==0){
            info=realizaCiclo(1, 25,pdu,snmp,comtarget );
            Info modelo_switch=new Info(model[1],true);
            info.add(modelo_switch);
        }
        if(model[1].compareTo("C2960")==0){//modelo gigabyte 
             info=realizaCiclo(10101,10125,pdu,snmp,comtarget );
             Info modelo_switch=new Info(model[1],true);
             info.add(modelo_switch);
        }
        /*
        for(int i=0;i<info.size();i++){
            Info we=(Info) info.get(i);
            System.out.println(we.getEstado()+ " "+we.getPuerto());
        }
        for (Info we :  info){
            System.out.println(we.getEstado()+ " "+we.getPuerto());
        } */
        snmp.close();
        return info;
    }

    public  ArrayList realizaCiclo(int p1, int p2,PDU pdu, Snmp snmp,
            CommunityTarget comtarget ) throws IOException{
        int numPuerto=0;
        ArrayList info=new ArrayList();
        for(int i=p1 ;i<p2;i++){
            String status="1.3.6.1.2.1.2.2.1.8."+i; // 1=prendido 2=apagado
            String name="1.3.6.1.2.1.2.2.1.2."+i; // descripcion (nombre)
            //Create the PDU object
            // giga 10101 - 10125 | 10149
            // fast 1 - 25 |  49
            pdu.add(new VariableBinding(new OID(status)));
            pdu.setType(PDU.GET);
            pdu.setRequestID(new Integer32(1));
            pdu.add(new VariableBinding(new OID(name)));
            pdu.setType(PDU.GET);
            pdu.setRequestID(new Integer32(1));
            
            // Create Snmp object for sending data to Agent
            ResponseEvent response = snmp.get(pdu, comtarget);
            
            // Process Agent Response
            if (response != null){
                PDU responsePDU = response.getResponse(); 
                if (responsePDU != null){
                    int errorStatus = responsePDU.getErrorStatus();
                    int errorIndex = responsePDU.getErrorIndex();
                    String errorStatusText = responsePDU.getErrorStatusText();
                    if (errorStatus == PDU.noError){
                        Vector datos=new Vector();
                        datos=responsePDU.getVariableBindings();
                        //  System.out.println(datos);
                        String[] estado=datos.get(0).toString().split("=");
                        String[] interfaz=datos.get(1).toString().split("/");
                        if(estado[1].compareTo(" 1")==0){
                            Info infoDatos=new Info(interfaz[1],true);
                            info.add(infoDatos);
                            // System.out.println("prendido "+interfaz[1]);
                        }else{
                            Info infoDatos=new Info(interfaz[1],false);
                            info.add(infoDatos);
                            //System.out.println("apagado "+interfaz[1]);
                        }
                        numPuerto++;
                        pdu.clear();
                    }else{
                        System.out.println("Error: Request Failed");
                        System.out.println("Error Status = " + errorStatus);
                        System.out.println("Error Index = " + errorIndex);
                        System.out.println("Error Status Text = " + errorStatusText);
                    }
                }else{
                    System.out.println("Error: Response PDU is null");
                }
            }else{
                System.out.println("Error: Agent Timeout... ");
            }
        }    
        return info;
    }


    public ArrayList snmp_virtual(){
        ArrayList lista=new ArrayList();
        lista.add( new Info("1",true));
        lista.add( new Info("2",true));
        lista.add( new Info("3",false));
        lista.add( new Info("4",false));
        lista.add( new Info("5",false));
        lista.add( new Info("6",false));
        lista.add( new Info("7",false));
        lista.add( new Info("8",false));
        lista.add( new Info("9",true));
        lista.add( new Info("10",true));
        lista.add( new Info("11",false));  
        lista.add( new Info("12",false));  
        lista.add( new Info("13",false));  
        lista.add( new Info("14",false));  
        lista.add( new Info("15",true));  
        lista.add( new Info("16",false));  
        lista.add( new Info("17",false));  
        lista.add( new Info("18",false));  
        lista.add( new Info("19",false));  
        lista.add( new Info("20",false));  
        lista.add( new Info("21",false));  
        lista.add( new Info("22",false));  
        lista.add( new Info("23",false));  
        lista.add( new Info("24",false));  
        lista.add( new Info("C3550",false));  
        return lista;
    }
public ArrayList snmp_virtual2(){
    ArrayList lista=new ArrayList();
    lista.add( new Info("1",false));
    lista.add( new Info("2",true));
    lista.add( new Info("3",false));
    lista.add( new Info("4",false));
    lista.add( new Info("5",false));
    lista.add( new Info("6",false));
    lista.add( new Info("7",false));
    lista.add( new Info("8",false));
    lista.add( new Info("9",true));
    lista.add( new Info("10",true));
    lista.add( new Info("11",false));  
    lista.add( new Info("12",false));  
    lista.add( new Info("13",false));  
    lista.add( new Info("14",false));  
    lista.add( new Info("15",false));  
    lista.add( new Info("16",false));  
    lista.add( new Info("17",true));  
    lista.add( new Info("18",false));  
    lista.add( new Info("19",false));  
    lista.add( new Info("20",false));  
    lista.add( new Info("21",false));  
    lista.add( new Info("22",false));  
    lista.add( new Info("23",false));  
    lista.add( new Info("24",false));  
    lista.add( new Info("C3550",false));  
    return lista;
}
}